<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" size="small" @click="addDialogVisible = true">新增</el-button>
        </el-col>
      </el-row>
      <el-table :data="evaluationList" border stripe v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading">
        <el-table-column label="封面图">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              :title="scope.row.name"
              trigger="hover">
              <img :src="scope.row.url.url" style="max-height: 200px;max-width: 200px"/>
              <img slot="reference" :src="scope.row.url.url" style="max-height: 50px;max-width: 50px"/>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="column_name" label="栏目"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="delEval(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="dialog_title" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!--内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px" class="demo-ruleForm">
        <el-form-item label="类别" prop="column_id">
          <el-select v-model="addForm.column_id" placeholder="请选择服务质量类别" style="width: 100%">
            <el-option v-for="(item,index) in eTypeList" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="img" ref="imageRef">
          <el-upload
            ref="imgref"
            :action="upload.url"
            :headers="upload.headers"
            :accept="upload.accept"
            list-type="picture-card"
            :file-list="addForm.img"
            :data="upload.data"
            :limit="upload.limitCount"
            :on-remove="handleRemove"
            :on-exceed="onExceed"
            :on-success="onSuccess"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-row :gutter="20" v-for="(item, index) in addForm.moreNotifyObject" :key="item.key">
          <el-col :span="20">
            <el-form-item :label="'服务案例' + index">
              <el-input v-model="item.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="removeCase(item)">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="content">
          <quill_edit v-model="addForm.content" :quillIndex="1" toref="Evalu"></quill_edit>
<!--          <quill_edit v-model="addForm.content"></quill_edit>-->
        </el-form-item>
      </el-form>
      <!--底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addDomain">添加测评案例</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addEvaluation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import quill_edit from '../../cheditor'

export default {
  name: "index",
  components: {
    quill_edit
  },
  data() {
    let checkImg = (rule, value, callback) => {
      if (!this.hasFmt) { //hasFmt设置为true/false
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    }
    return {
      addDialogVisible: false,
      dialog_title: '新增',
      hasFmt: false,
      evaluationList: [],
      addForm: {
        img: [],
        column_id: '',
        content: '',
        moreNotifyObject: [
          {
            title: '',
          }
        ]
      },
      queryInfo: {
        title: '',
        limit: this.$global_limit,
        page: this.$global_page
      },
      loading: true,
      total: 0,
      addFormRules: {
        img: [{required: true, validator: checkImg}],
        column_id: [
          {required: true, message: '请选择所属类型', trigger: 'change'}
        ]
      },
      upload: {
        url: this.$action_url,
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data: {
          folder: 'evaluation_img'
        },
        name: 'file',
        accept: 'image/*',
        limitCount: 1,
      },
      eTypeList: [],
    }
  },
  created() {
    this.typeList()
    this.getEvaluationList()
  },
  methods: {
    //列表
    async getEvaluationList() {
      const {data: res} = await this.$http.get('dashboard/evaluation_list', {params: this.queryInfo})
      if (res.code !== 200) return this.$message.error(res.data.message)
      this.evaluationList = res.data.list
      this.total = res.data.totalCount
      this.loading = false
    },
    async typeList() {
      const {data: res} = await this.$http.get('dashboard/evaluation_type_list')
      if (res.code !== 200) return this.$message.error('获取类别失败');
      this.eTypeList = res.data.list;
    },
    addDialogClose() {
      this.addForm.moreNotifyObject = [
        {
          title: '',
        }
      ];
      this.$refs.imgref.clearFiles()
      this.$refs.addFormRef.resetFields()
    },
    handleSizeChange(newSize) {
      this.queryInfo.limit = newSize
      this.getEvaluationList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getEvaluationList()
    },
    handleRemove(file) {
      const i = this.addForm.img.findIndex(x => x.image === file)
      //通过数组的splice方法 把图片从img_path 数组中删除
      this.addForm.img.splice(i, 1)
      if (this.addForm.img.length === 0) {
        this.hasFmt = false;
      }
      this.$refs.imageRef.validate();
    },
    onExceed(files, fileList) {
      if (files.length === 1) {
        return this.$message.error('图片超出1张图片的限制,请删除后重新上传')
      }
    },

    onSuccess(response, file, fileList) {
      if (response.code !== 200) return this.$message.error(response.data.message)
      this.hasFmt = true;
      const path = {url: this.$http_url + 'storage/' + response.data.list.path, uid: file.uid, name: file.name}
      this.addForm.img.push(path)
      this.$refs.imageRef.clearValidate();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    addEvaluation() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/save_evaluation', this.addForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('新增成功')

        this.addDialogVisible = false
        this.addForm.id = 0;
        this.dialog_title = '新增'

        this.getEvaluationList()
      })
    },
    async showEditDialog(id) {
      this.dialog_title = '编辑'
      this.addDialogVisible = true
      this.hasFmt = true;
      const {data: res} = await this.$http.get('dashboard/show_eval/' + id)
      if (res.code !== 200) return this.$message.error('获取失败');
      this.addForm = res.data.list;
    },
    //删除
    async delEval(id) {
      const configResult = await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (configResult !== 'confirm') return this.$message.info('已取消删除')
      const {data: result} = await this.$http.delete('dashboard/del_eval/' + id)
      if (result.code !== 200) return this.$message.error(result.data.message)
      this.$message.success('删除成功')

      //删除成功后页码改变返还为上一页
      let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
      let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
      this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;

      this.getEvaluationList();
    },
    removeCase(item) {
      let index = this.addForm.moreNotifyObject.indexOf(item)
      if (index !== -1) {
        this.addForm.moreNotifyObject.splice(index, 1)
      }
    },
    addDomain() {
      this.addForm.moreNotifyObject.push({
        title: ''
      })
    },
  }
}
</script>

<style scoped>

</style>
